import dateFormat from 'dateformat';
import MD5 from 'md5';

export default {
	install(Vue) {
		/** 下载
		 * @param {string} url
		 * */
		Vue.prototype.$downLoad = url => {
			let a = document.createElement("a");
			a.href = url;
			document.body.appendChild(a);
			a.click();
		}

		Vue.prototype.$dateFormat = dateFormat;
		Vue.prototype.$MD5 = MD5;

		/** 
		 * 数组去重
		 * @param {Array} array
		*/
		Vue.prototype.$dedupe = array => {
			return Array.from(new Set(array));
		}

		/** 时间转化
		 * @param {(Object|string|number)} time
		 * @param {string} cFormat
		 * @returns {string}
		 */
		Vue.prototype.$parseTime = (time, cFormat) => {
			if (!time) return false;
			if (arguments.length === 0) {
				return null
			}
			const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
			let date
			if (typeof time === 'object') {
				date = time
			} else {
				if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
					time = parseInt(time)
				}
				if ((typeof time === 'number') && (time.toString().length === 10)) {
					time = time * 1000
				}
				date = new Date(time)
			}
			const formatObj = {
				y: date.getFullYear(),
				m: date.getMonth() + 1,
				d: date.getDate(),
				h: date.getHours(),
				i: date.getMinutes(),
				s: date.getSeconds(),
				a: date.getDay()
			}
			const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
				let value = formatObj[key]
				if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
				if (result.length > 0 && value < 10) {
					value = '0' + value
				}
				return value || 0
			})
			return time_str
		}
		
		/** 时间转化
		 * @param {(Object|string|number)} endDateStr
		 * @returns {string}
		 */
		Vue.prototype.$formatTime = endDateStr => {
			if (!endDateStr) return null;
			// 结束时间
			var endDate = new Date(endDateStr);
			// 当前时间
			var nowDate = new Date();
			// 相差的总秒数
			var totalSeconds = parseInt((endDate - nowDate) / 1000);
			// 天数
			var days = Math.floor(totalSeconds / (60 * 60 * 24));
			// 取模（余数）
			var modulo = totalSeconds % (60 * 60 * 24);
			// 小时数
			var hours = Math.floor(modulo / (60 * 60));
			modulo = modulo % (60 * 60);
			// 分钟
			var minutes = Math.floor(modulo / 60);
			// 秒
			// var seconds = modulo % 60;
			return days + "天" + hours + "小时" + minutes + "分钟后执行";
		}

		/** 获取URL Query 对象
		 * @param {string} url
		 * @returns {Object}
		 */
		Vue.prototype.$getQueryObject = url => {
			url = url == null ? window.location.href : url
			const search = url.substring(url.lastIndexOf('?') + 1)
			const obj = {}
			const reg = /([^?&=]+)=([^?&=]*)/g
			search.replace(reg, (rs, $1, $2) => {
				const name = decodeURIComponent($1)
				let val = decodeURIComponent($2)
				val = String(val)
				obj[name] = val
				return rs
			})
			return obj
		}

		/** 浅拷贝
		 * @param {Array} actual
		 * @returns {Array}
		 */
		const cleanArray = actual => {
			const newArray = []
			for (let i = 0; i < actual.length; i++) {
				if (actual[i]) {
					newArray.push(actual[i])
				}
			}
			return newArray
		}

		Vue.prototype.$cleanArray = cleanArray;

		/** 把json 拼接成 prams
		 * @param {Object} json
		 * @returns {Array}
		 */
		Vue.prototype.$param = json => {
			if (!json) return ''
			return cleanArray(
				Object.keys(json).map(key => {
					if (json[key] === undefined) return ''
					return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
				})
			).join('&')
		}

		/** 通过 query 参数
		 * @param {string} url
		 * @returns {Object}
		 */
		Vue.prototype.$param2Obj = url => {
			const search = url.split('?')[1]
			if (!search) {
				return {}
			}
			return JSON.parse(
				'{"' +
				decodeURIComponent(search)
					.replace(/"/g, '\\"')
					.replace(/&/g, '","')
					.replace(/=/g, '":"')
					.replace(/\+/g, ' ') +
				'"}'
			)
		}

		/** 合并json
		 * @param {Object} target
		 * @param {(Object|Array)} source
		 * @returns {Object}
		 */
		const objectMerge = (target, source) => {
			if (typeof target !== 'object') {
				target = {}
			}
			if (Array.isArray(source)) {
				return source.slice()
			}
			Object.keys(source).forEach(property => {
				const sourceProperty = source[property]
				if (typeof sourceProperty === 'object') {
					target[property] = objectMerge(target[property], sourceProperty)
				} else {
					target[property] = sourceProperty
				}
			})
			return target
		}

		Vue.prototype.$objectMerge = objectMerge;

		/** 获取当前时间
		 * @param {string} type
		 * @returns {Date}
		 */
		Vue.prototype.$getTime = type => {
			if (type !== 'timer') {
				return new Date().getTime() - 3600 * 1000 * 24 * 90
			} else {
				return new Date(new Date().toDateString())
			}
		}


		/** 深拷贝
		 * @param {Object} source
		 * @returns {Object}
		 */
		const deepClone = source => {
			if (!source && typeof source !== 'object') {
				throw new Error('error arguments', 'deepClone')
			}
			const targetObj = source.constructor === Array ? [] : {}
			Object.keys(source).forEach(keys => {
				if (source[keys] && typeof source[keys] === 'object') {
					targetObj[keys] = deepClone(source[keys])
				} else {
					targetObj[keys] = source[keys]
				}
			})
			return targetObj
		}

		Vue.prototype.$deepClone = deepClone;

		/** 新数组
		 * @param {Array} arr
		 * @returns {Array}
		 */
		Vue.prototype.$uniqueArr = arr => {
			return Array.from(new Set(arr))
		}

		/** 创建一个 唯一的 字符串
		 * @returns {string}
		 */
		Vue.prototype.$createUniqueString = () => {
			const timestamp = +new Date() + ''
			const randomNum = parseInt((1 + Math.random()) * 65536) + ''
			return (+(randomNum + timestamp)).toString(32)
		}

		/** 查询字典
		 * @param {Array} arr
		 * @param {Int} id
		 * @param {String} key
		 * @param {String} name
		 */
		Vue.prototype.$queryDic = (arr, id, name = 'dictValue', key = 'id') => {
			for (let i = 0; i < arr.length; i++) {
				if (arr[i][key] + '' === id + '') return arr[i][name];
			}
		}

		/** 把树形结构展开为一维数组
		 * @param { Array } tree 树
		 * @param { String } children
		 * @return { Array }
		*/

		const recursion = (data, children) => {
			if (!data) return [];
			if (data[children] && data[children].length) {
				const item = _.clone(data);
				delete item[children];
				let datas = [];
				data[children].concat(item).forEach(item => {
					datas = datas.concat(recursion(item, children));
				});
				return datas;
			}
			return data;
		};

		Vue.prototype.$openTree = (tree = [], children = 'children') => {
			let data = [];
			_.each(tree, item => {
				data = data.concat(recursion(item, children));
			});
			return data;
		}

		/**
		 * 给定元素查找它的上一个兄弟节点
		 * @param ele
		 * @return {Element}
		 */
		Vue.prototype.$getPrevNode = ele => {
			return ele.previousElementSibling || ele.previousSibling;
		}
	}
}